package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.MallAuditCertifyInfoStatusType;
import com.rockcent.mall.lib.domain.enumclass.MallMemberStatus;
import com.rockcent.mall.lib.domain.enumclass.SysMessageType;
import com.rockcent.mall.lib.dto.LocationDto;
import com.rockcent.mall.lib.dto.MallCertifyInfoDTO;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.LocationHelper;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Created by DK on 17/3/2.
 * 平台管理
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class MallMemberAptitudeController extends BaseController{
    private final Logger log = LoggerFactory.getLogger(MallMemberAptitudeController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private LocationHelper locationHelper;

    @Autowired
    private MallCertifyInfoRepository mallCertifyInfoRepository;

    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MallCertifyInfoAuditRecordRepository mallCertifyInfoAuditRecordRepository;

    @Autowired
    private MallMemberRepository mallMemberRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;

    /**
     * @api {get} /v1/mall/member/aptitude/info_page R 平台管理 平台资质信息 分页
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=ALL("全部或者已审核"), AUDIT("待审核"), AUDIT_PASS("审核通过"), NOT_AUDIT("审核不通过")} status <code>必传参数</code> 审核状态
     * @apiParam {String} mallName 平台名称
     * @apiParam {String} mobile 联系人手机号
     * @apiParam {String} beginTime 开始时间
     * @apiParam {String} endTime 结束时间
     *
     * @apiSuccess {long} id ID
     * @apiSuccess {long} mallId 平台ID
     * @apiSuccess {String} mallName 平台名称
     * @apiSuccess {String} companyName 公司名称
     * @apiSuccess {String} mobile 联系人手机号
     * @apiSuccess {String} status 审核状态
     * @apiSuccess {date} dateCreated 提交时间
     * @apiSuccess {date} dateAudited 审核时间
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data" : [
     *          {
     *              "id" : 12
     *              "mallId" : 2,
     *              "mallName" : "乐橙",
     *              "companyName" : "乐城公司",
     *              "mobile" : "13678632352",
     *              "dateCreated" : "2017-01-10 18:32:47",
     *              "dateAudited" : "2017-01-10 18:32:47",
     *              "status" : "AUDIT"
     *          },
     *          .......
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MALL_MEMBER_APTITUDE_INFO_PAGE, method = RequestMethod.GET)
    public JsonResult mallAptitudeInfoPage(HttpServletRequest request, MallCertifyInfoDTO dto) {
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getStatus()) || !EnumUtils.isValidEnum(MallAuditCertifyInfoStatusType.class, dto.getStatus())) {
                jsonResult.remind("审核状态只允许 ALL(\"全部或者已审核\"), AUDIT(\"待审核\"), AUDIT_PASS(\"审核通过\"), NOT_AUDIT(\"审核不通过\")",log);
                return;
            }
            PageResult<MallCertifyInfoDTO> pageResult = mallCertifyInfoRepository.mallAptitudeInfoPage(dto.getMallName(), dto.getMobile(), dto.getBeginTime(), dto.getEndTime(), dto.getStatus(), this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MALL_MEMBER_APTITUDE_INFO_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/member/aptitude/info R 平台管理 平台资质信息 详情
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必传参数</code> id
     *
     * @apiSuccess {long} id ID
     * @apiSuccess {String} companyName 公司名称
     * @apiSuccess {String} organizationCode 组织机构代码
     * @apiSuccess {String} businessLicenseElectronic 营业执照副本电子版
     * @apiSuccess {String} industry 经营行业
     * @apiSuccess {String} nameOfCompanyLegal 法人代表姓名
     * @apiSuccess {String} idCardNumber 身份证号码
     * @apiSuccess {String} idCardNumberElectronic 法人身份证电子版
     * @apiSuccess {String} bankAccountName 银行开户名
     * @apiSuccess {String} bankAccount 公司银行账号
     * @apiSuccess {String} bankName 开户银行支行名称
     * @apiSuccess {String} bankSerialNum 开户银行支行联行号
     * @apiSuccess {String} bankPermitElectronic 开户银行许可证电子版
     * @apiSuccess {String} companyLocation 公司所在地
     * @apiSuccess {String} bankLocation 银行卡开卡所在地
     * @apiSuccess {String} mobile 联系人手机号码
     * @apiSuccess {String} email 联系人邮箱
     * @apiSuccess {Long} mallId 平台id
     * @apiSuccess {Date} recordList_dateCreated 时间
     * @apiSuccess {String} recordList_status 状态
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data" :
     *          {
     *              "companyName": "广州乐宸网络科技有限公司",
     *              "organizationCode": "35rete564654",
     *              "businessLicenseElectronic": "http://uploads.rockcent.com/20160803/201608031045227nndznhk.png",
     *              "industry": "网络技术的研究",
     *              "nameOfCompanyLegal": "黄乐钊",
     *              "idCardNumber": "440802197604020417",
     *              "idCardNumberElectronic": "http://uploads.rockcent.com/20160803/20160803105206E1aWhuYT.png",
     *              "bankAccountName": "广州乐宸",
     *              "bankAccount": "120908294410333",
     *              "bankName": "招商银行股份有限公司广州金穗支行",
     *              "bankSerialNum": "120908294410333",
     *              "bankPermitElectronic": "http://uploads.rockcent.com/20160803/20160803105411LyAFthv6.jpg",
     *              "mallId": 1,
     *              "proviceId": "广东",
     *              "cityId": "广州",
     *              "zoneId": "海珠",
     *              "companyProviceId": "广东",
     *              "companyCityId": "广州",
     *              "companyZoneId": "海珠",
     *              "mobile": "13567899876",
     *              "email": "4123@qq.com",
     *              "recordList" : [
     *                          {
     *                              "dateCreated" : "2017-01-10 18:32:47",
     *                              "status" : "NOT_AUDIT"
     *                          }
     *              ]
     *          }
     * }
     */
    @RequestMapping(value = Routes.MALL_MEMBER_APTITUDE_INFO, method = RequestMethod.GET)
    public JsonResult mallAptitudeInfo (HttpServletRequest request, MallCertifyInfoDTO dto){
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MallCertifyInfo.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }

            MallCertifyInfoDTO mallCertifyInfo = mallCertifyInfoRepository.findMallCertifyInfoById(dto.getId());
            if (mallCertifyInfo == null) {
                jsonResult.remind(MallCertifyInfo.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }

            Mall mall = mallRepository.findOne(mallCertifyInfo.getMallId());
            if (mall == null) {
                jsonResult.remind("审核平台不存在",log);
                return;
            }

            UserInfo userInfo = userInfoRepository.findOne(mall.getUserInfoId());
            if (userInfo == null) {
                jsonResult.remind("信息有误,请联系开发人员",log);
                return;
            }

            //开户银行所在地
            if(mallCertifyInfo.getLocationId() != null) {
                LocationDto locationDto = locationHelper.getFullLocation(mallCertifyInfo.getLocationId());
                if (locationDto != null) {
                    mallCertifyInfo.setBankLocation(locationDto.getProviceName() + locationDto.getCityName() + locationDto.getLocationName());
                }
            }
            //公司所在地
            if(mallCertifyInfo.getCompanyLocationId() != null) {
                LocationDto companyLocationDto = locationHelper.getFullLocation(mallCertifyInfo.getCompanyLocationId());
                if (companyLocationDto != null) {
                    mallCertifyInfo.setCompanyLocation(companyLocationDto.getProviceName() + companyLocationDto.getCityName() + companyLocationDto.getLocationName());
                }
            }
            mallCertifyInfo.setMobile(userInfo.getMobile());
            mallCertifyInfo.setEmail(userInfo.getEmail());
            List<MallCertifyInfoAuditRecord> recordList = mallCertifyInfoAuditRecordRepository.findByMallId(mallCertifyInfo.getMallId());
            mallCertifyInfo.setRecordList(recordList);
            jsonResult.data = mallCertifyInfo;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/mall/member/aptitude/info_audit R 平台管理 平台资质信息 审核
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=AUDIT_PASS("审核通过"), NOT_AUDIT("审核不通过")} status <code>必传参数</code> 审核状态
     * @apiParam {Long} id <code>必传参数</code> id
     * @apiParam {String} auditRemark 审核意见 (备注:审核不通过时,审核意见不能为空)
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_MEMBER_APTITUDE_INFO_AUDIT, method = RequestMethod.PUT)
    public JsonResult auditMallAptitudeInfo (HttpServletRequest request, @RequestBody MallCertifyInfoDTO dto){
        UserInfoDto userInfo = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MallCertifyInfo.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            if (StringUtils.isBlank(dto.getStatus()) || !EnumUtils.isValidEnum(MallAuditCertifyInfoStatusType.class, dto.getStatus())) {
                jsonResult.remind("审核状态只允许 AUDIT_PASS(\"审核通过\"), NOT_AUDIT(\"审核不通过\")",log);
                return;
            }
            MallCertifyInfo certifyInfo = mallCertifyInfoRepository.findOne(dto.getId());
            if (certifyInfo == null) {
                jsonResult.remind(MallCertifyInfo.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            Mall mall = mallRepository.findOne(certifyInfo.getMallId());
            if (mall == null) {
                jsonResult.remind("平台不存在",log);
                return;
            }

            if (MallAuditCertifyInfoStatusType.AUDIT != mall.getAuditCertifyInfoStatus()) {
                jsonResult.remind("资质信息有误, 请联系开发人员",log);
                return;
            }

            MallCertifyInfoAuditRecord record = new MallCertifyInfoAuditRecord();
            SysMessageConstants sysMessageConstants = null;
            String content = null;
            if (MallAuditCertifyInfoStatusType.AUDIT_PASS == MallAuditCertifyInfoStatusType.valueOf(dto.getStatus())) {
                mall.setAuditCertifyInfoStatus(MallAuditCertifyInfoStatusType.AUDIT_PASS);
                mall.setAuditCertifyInfoRemark("通过");
                mall.setAuditValidate(Whether.YES);
                record.setStatus(MallAuditCertifyInfoStatusType.AUDIT_PASS.toString());

                //审核通过之后, 默认试用期三十天
                MallMember mallMember = mallMemberRepository.findByMallIdAndIsDelete(mall.getId(), Whether.NO);
                mallMember.setDateEnabled(RDateUtils.afterDateStr(RDateUtils.date2String(DateUtils.getCurrentDate(), null), 0));
                mallMember.setDateDisabled(RDateUtils.afterDateStr(RDateUtils.date2String(DateUtils.getCurrentDate(), null), 30));
                mallMember.setProbationaryPeriodDays(30L);
                mallMember.setStatus(MallMemberStatus.PROBATION_MEMBER);
                mallMemberRepository.save(mallMember);

                sysMessageConstants = SysMessageConstants.M2M_MALL_MEMBER_APTITUDE_AUDIT_PASSS;
            }
            if (MallAuditCertifyInfoStatusType.NOT_AUDIT == MallAuditCertifyInfoStatusType.valueOf(dto.getStatus())) {
                if (StringUtils.isBlank(dto.getAuditRemark())) {
                    jsonResult.remind("审核意见 不能为空",log);
                    return;
                }
                mall.setAuditCertifyInfoStatus(MallAuditCertifyInfoStatusType.NOT_AUDIT);
                mall.setAuditCertifyInfoRemark(dto.getAuditRemark());
                record.setStatus(MallAuditCertifyInfoStatusType.NOT_AUDIT.toString());

                String constantContent = SysMessageConstants.M2M_MALL_MEMBER_APTITUDE_AUDIT_UNPASSS.getContent();
                content = MessageFormat.format(constantContent, dto.getAuditRemark());
                sysMessageConstants = SysMessageConstants.M2M_MALL_MEMBER_APTITUDE_AUDIT_UNPASSS;
            }

            record.setMallId(mall.getId());
            record.setOperatorId(userInfo.getId());

            mall.setDateAudited(new Date());
            mallRepository.save(mall);
            mallCertifyInfoAuditRecordRepository.save(record);

            //广播消息
            SysMessageHelper.SINGLETON.pushSysMsg(sysMessageConstants, content, mall.getId(),null);
        };
        return doing.go(request, log);
    }

}
